package it.eng.area118.mdocommon.android.ntp;

import it.eng.area118.mdocommon.android.log.BasicLogger;
import it.eng.area118.mdocommon.android.model.AndroidModelContainer;
import it.eng.area118.mdocommon.android.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class NtpSynchReceiver extends BroadcastReceiver {

	private Calendar calendar = null;

	@Override
	public void onReceive(Context ctx, Intent i) {
		// try {
		// lock.lock();
		String action = i.getAction();
		if (StringUtils.isEmpty(action)) {
			BasicLogger.getLog().warn(
					"NtpSynchReceiver UNKNOWN ACTION: " + action);
			return;
		}

		if (action.equals("SYNCH")) {
			Calendar c = (Calendar) i.getSerializableExtra("SYNCH");
			if (c != null) {
				BasicLogger.getLog().info(
						"IN NTP RECEIVER: "
								+ i.getAction()
								+ " - "
								+ new SimpleDateFormat("dd/MM/yyyy HH:mm:ss")
										.format(c.getTime()));
			}
			calendar = (Calendar) i.getSerializableExtra("SYNCH");
			if (calendar != null) {
				AndroidModelContainer.getInstance().putModel("CURRENT_TIME",
						((Calendar) calendar.clone()), true);
			}
		} else if (action.equals("TICK")) {

			Calendar currentTime = (Calendar) AndroidModelContainer
					.getInstance().getModel("CURRENT_TIME");
			if (currentTime != null) {
				currentTime.add(Calendar.SECOND, 1);
				AndroidModelContainer.getInstance().putModel("CURRENT_TIME",
						currentTime, true);
			}

		} else if (action.equals("RESUME")) {
			Calendar currentTime = (Calendar) AndroidModelContainer
					.getInstance().getModel("CURRENT_TIME");
			if (currentTime != null) {
				int secs = i.getIntExtra("OFFSET", 0);
				currentTime.add(Calendar.SECOND, secs);

				AndroidModelContainer.getInstance().putModel("CURRENT_TIME",
						currentTime, true);
			}

		}

	}
}
